package com.metis.document.parse.dialog.pipeline.impl;

import com.metis.document.parse.dialog.pipeline.TextPostProcess;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class UnicodeCharsPostProcess implements TextPostProcess {

    private final static String skip_char_list = "，：、";

    @Override
    public String process(@NotNull String input) {
        StringBuilder output = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (skip_char_list.contains(String.valueOf(ch))){
                output.append(ch);
                continue;
            }
            if (ch == 12288) { // 全角空格转换为半角空格
                output.append(' ');
            } else if (ch >= 65281 && ch <= 65374) { // 全角字符转换为半角字符
                output.append((char) (ch - 65248));
            } else if (Character.isHighSurrogate(ch) && i + 1 < input.length() && Character.isLowSurrogate(input.charAt(i + 1))) {
                // 处理代理对
                int surrogatePair = Character.toCodePoint(ch, input.charAt(++i));
                if (surrogatePair >= 65281 && surrogatePair <= 65374) {
                    output.append((char) (surrogatePair - 65248));
                } else {
                    output.append(Character.toChars(surrogatePair));
                }
            } else {
                output.append(ch);
            }
        }
        return output.toString();
    }
}
